early_states <- first_substantial$state
# Filter data for these five states, focusing on early pandemic period
early_states_data <- covid_data %>%
filter(state %in% early_states,
date >= as.Date("2020-03-01"),
date <= as.Date("2020-07-01"))
colors <- c('#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd')
# Create the plotly visualization
fig3 <- plot_ly()
# Add a trace for each of the five states
for (i in 1:length(early_states)) {
state_data <- early_states_data %>% filter(state == early_states[i])
fig3 <- fig3 %>%
add_trace(
data = state_data,
x = ~date,
y = ~cases_avg_per_100k,
type = 'scatter',
mode = 'lines',
name = early_states[i],
line = list(color = colors[i], width = 2.5),
hovertemplate = paste(
'<b>', early_states[i], '</b><br>',
'Date: %{x|%Y-%m-%d}<br>',
'Cases per 100k: %{y:.1f}<br>',
'<extra></extra>'
)
)
}
# Add vertical dashed lines showing when each state crossed the threshold
for (i in 1:nrow(first_substantial)) {
fig3 <- fig3 %>%
add_segments(
x = first_substantial$first_date[i],
xend = first_substantial$first_date[i],
y = 0,
yend = threshold,
line = list(color = colors[i], dash = 'dash', width = 1.5),
showlegend = FALSE,
hovertemplate = paste(
'<b>', first_substantial$state[i], '</b><br>',
'First crossed 5 per 100k<br>',
'Date: ', format(first_substantial$first_date[i], '%Y-%m-%d'),
'<extra></extra>'
)
)
}
# Add horizontal reference line at threshold
fig3 <- fig3 %>%
add_segments(
x = as.Date("2020-03-01"),
xend = as.Date("2020-07-01"),
y = threshold,
yend = threshold,
line = list(color = 'black', dash = 'dot', width = 1),
showlegend = FALSE,
name = "Threshold (5 per 100k)"
)
fig3 <- fig3 %>%
layout(
title = list(
text = "<b>First Five States to Experience Substantial COVID-19 Transmission</b><br><sub>Substantial defined as reaching 5 cases per 100,000 population (7-day average)</sub>",
font = list(size = 18, family = "Arial")
),
xaxis = list(
title = "<b>Date</b>",
titlefont = list(size = 14),
showgrid = TRUE,
gridcolor = '#E5E5E5',
showline = TRUE,
linecolor = 'black',
range = c(as.Date("2020-03-01"), as.Date("2020-07-01"))
),
yaxis = list(
title = "<b>7-Day Average Cases per 100,000 Population</b>",
titlefont = list(size = 14),
showgrid = TRUE,
gridcolor = '#E5E5E5',
showline = TRUE,
linecolor = 'black'
),
hovermode = 'closest',
plot_bgcolor = 'white',
paper_bgcolor = 'white',
legend = list(
orientation = 'v',
x = 1.02,
xanchor = 'left',
y = 1,
font = list(size = 11)
),
font = list(family = "Arial, sans-serif", size = 12),
margin = list(l = 80, r = 120, t = 100, b = 80),
annotations = list(
list(
x = 0.5,
y = -0.12,
xref = 'paper',
yref = 'paper',
text = 'Dashed vertical lines indicate when each state first reached 5 cases per 100k',
showarrow = FALSE,
font = list(size = 10, color = 'gray')
)
)
) %>%
config(displayModeBar = TRUE, displaylogo = FALSE,
modeBarButtonsToRemove = c('lasso2d', 'select2d'))
fig3